package com.gagakuai.bpm.config.security;

import com.gagakuai.bpm.domian.dto.camunda.WorkflowVariableDto;
import com.gagakuai.bpm.domian.events.CallBusinessStartProcessEvent;
import com.gagakuai.bpm.service.camunda.WorkflowTaskService;
import com.gagakuai.bpm.utils.UserUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/*
 * 自动发起流程服务
 */

@Slf4j
@Component
public class AutoStartProcInst implements JavaDelegate, ApplicationEventPublisherAware {
    @Resource
    private WorkflowTaskService workflowTaskService;

    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void execute(DelegateExecution execution) throws Exception {
        try{
            Object objKey = execution.getVariables().get("key");
            if(ObjectUtils.isEmpty(objKey)){
                log.info("发起流程失败，需要设置流程参数Key");
                return;
            }

            Object userIds = execution.getVariables().get("userIdList");
            if(ObjectUtils.isEmpty(userIds)){
                log.info("发起流程失败，需要设置参数：userIdList");
                return;
            }

            Object businessId = execution.getVariables().get("businessId");
            if(ObjectUtils.isEmpty(businessId)){
                log.info("发起流程失败，需要设置参数：businessId");
                return;
            }

            String[] assigneeArray = userIds.toString().split(",");
            String[] businessArray = businessId.toString().split(",");
            List<String> listBusinessIdAndProcInstId = new ArrayList<>();
            for (int i = 0; i < assigneeArray.length; i++) {
                WorkflowVariableDto workflowVariableDto = new WorkflowVariableDto();
                workflowVariableDto.setStartUser(execution.getVariables().getOrDefault("startUser", "demo").toString());
                workflowVariableDto.setBusinessId(businessArray[i]);
                workflowVariableDto.setTenantIds("");
                HashMap<String, Object> map = new HashMap<>();
                map.put("assignee", assigneeArray[i]);
                workflowVariableDto.setVariables(map);
                listBusinessIdAndProcInstId.add(String.join(",", businessArray[i], workflowTaskService.startProcess(objKey.toString(), workflowVariableDto)));
                map.put("userIds", listBusinessIdAndProcInstId);
            }

            applicationEventPublisher.publishEvent(new CallBusinessStartProcessEvent(applicationEventPublisher, execution.getBusinessKey(), listBusinessIdAndProcInstId, UserUtil.get().getToken()));
        }catch (Exception e){
            throw new Exception("自动发起流程异常", e);
        }
    }

    @Override
    public void setApplicationEventPublisher(@NonNull ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
